
/**
 * Level
 * Template of an instance level
 **/
var Level = function() {

	this.sprites = {
		// background : IM.getInstance('img/skybox')
	};

	this.w = WIDTH;
	this.h = HEIGHT;

	this.entities = [];
	this.axis = [];

	this.cA = 3;
	this.cE = 20;
	
	this.init = function(name) {
		// log('*** INIT LEVEL ***');

		// Set level position
		this.x = offset.x;
		this.y = offset.y;



		// Create axis trajectories
		for(var iA = 0; iA < this.cA; iA++) {
			// Create an axis
			var axis = {
				id:iA,
				x:this.x-offset.x,
				y:this.y-offset.y,
				w:this.w*(0.7*(iA+1)),
				h:this.h*(0.7*(iA+1))
			};
			// Set axis in level axis
			this.axis.push(axis);

			// Set number of island on this axis
			var cE = Math.round(this.cE/(this.cA-iA));
			// Set a constant for angle
			var N = ((Math.PI*2) / cE);

			// Create islands on this axis
			for(var iE = 0; iE < cE; iE++) {

				// Set angle according to partition
				var angle = N * iE - Math.PI/2;

				// create island
				var island = new Island();
				// Init with axis and angle parameters
				island.init(axis, angle);
				// Set island in level entities
				this.entities.push(island);
			}
		}
	}

	this.destroy = function() {

	}

	this.update = function() {
		// Start drag level
		if(input.mouse.click == true) {
			this.offset = input.drag(this);
		}

		// Update level position according to drag action
		if(input.mouse.drag == true) {
		    this.x = input.mouse.x - this.offset.x;
		    this.y = input.mouse.y - this.offset.y;
		}

		// Update axis position according to new level position
		for(var iA = 0, c = this.axis.length; iA < c; iA++) {
			var axis = this.axis[iA];
			axis.x = this.x-offset.x;
		    axis.y = this.y-offset.y;
		}

		// Update islands
		for(var iE = 0, c = this.entities.length; iE < c; iE++) {
			this.entities[iE].update();
		}
	}

	this.render = function() {
		// Clean canvas with large black square
		drawRect(CTX,"#000",0,0,this.w,this.h);

		// Draw level background
		// IM.drawImage(CTX, this.sprites.background, this.x, this.y);
		drawRect(CTX,"#CCC",this.x,this.y,this.w*2,this.h*2);

		// Draw ellipse trajectories
		for(var iA = 0, c = this.axis.length; iA < c; iA++) {
			var axis = this.axis[iA];
			drawEllipseByCenter(CTX,"rgba(0,0,255,.8)",axis.x,axis.y,axis.w,axis.h);
			// Debug: draw circle
			// drawCircle(CTX,"rgba(255,0,0,.8)",axis.x,axis.y,axis.w,0,Math.PI*2,5);
		}

		// Draw islands
		for(var iE = 0, c = this.entities.length; iE < c; iE++) {
			this.entities[iE].render();
		}
	}

};